<template>
  <view class="recommend-container">
    <!-- 顶部Tab切换 -->
    <view class="tab-bar">
      <view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
        @tap="switchTab(index)">
        <text class="tab-text">{{ tab.name }}</text>
        <view v-if="currentTab === index" class="tab-indicator"></view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && videoList.length === 0" class="empty-video-placeholder">
      <view class="empty-video-card">
        <text class="empty-icon">🎬</text>
        <text class="empty-title">暂时没有可播放的视频</text>
        <text class="empty-desc">去发布页面上传作品，精彩内容等你来！</text>
        <view class="empty-action" @tap="loadVideos">刷新试试</view>
      </view>
    </view>

    <!-- 视频流 -->
    <swiper v-else class="video-swiper" :current="currentVideoIndex" :vertical="true" :circular="false"
      @change="onVideoChange" @transition="onVideoTransition">
      <swiper-item v-for="(video, index) in videoList" :key="video.id || index" class="video-item-wrapper">
        <view class="video-item">
          <!-- 视频播放器 -->
          <video class="video-player" :src="video.videoUrl" :poster="video.videoCover"
            :id="`video-${video.id || index}`" :data-index="index" :show-center-play-btn="false" :show-play-btn="false"
            :enable-play-gesture="true" :object-fit="'cover'" :muted="false" :loop="true" :autoplay="index === 0"
            @play="onVideoPlay" @pause="onVideoPause" @ended="onVideoEnded" @error="onVideoError"></video>

          <!-- 视频信息遮罩层 -->
          <view class="video-overlay">
            <!-- 左侧：用户信息和描述 -->
            <view class="video-info-left">
              <view class="author-info" @tap="goToUserProfile(video.authorId)">
                <view class="author-avatar-wrapper">
                  <image class="author-avatar" :src="video.author?.avatar || '/static/logo.png'" mode="aspectFill">
                  </image>
                  <view v-if="video.authorId !== currentUserId && !video.isFollowed" class="follow-plus"
                    @tap.stop="handleFollowAuthor(video)">
                    <text class="plus-icon">{{ video.followLoading ? '···' : '+' }}</text>
                  </view>
                  <view v-else-if="video.authorId !== currentUserId && video.isFollowed" class="followed-badge">
                    <text class="followed-text">已关注</text>
                  </view>
                </view>
                <text class="author-name">{{ video.author?.username || '用户' }}</text>
              </view>
              <view class="video-description">
                <text class="description-text">{{ video.title || video.description }}</text>
              </view>
              <view v-if="video.tags && video.tags.length > 0" class="video-tags">
                <text v-for="(tag, idx) in video.tags" :key="idx" class="tag">#{{ tag }}</text>
              </view>
            </view>

            <!-- 右侧：互动按钮 -->
            <view class="video-actions-right">
              <view class="action-item" @tap="toggleLike(video)">
                <view class="action-icon-wrapper">
                  <text class="action-icon" :class="{ liked: video.isLiked }">❤️</text>
                </view>
                <text class="action-count">{{ formatCount(video.likesCount) }}</text>
              </view>
              <view class="action-item" @tap="goToComments(video.id)">
                <view class="action-icon-wrapper">
                  <text class="action-icon">💬</text>
                </view>
                <text class="action-count">{{ formatCount(video.commentsCount) }}</text>
              </view>
              <view class="action-item" @tap="toggleCollect(video)">
                <view class="action-icon-wrapper">
                  <text class="action-icon" :class="{ collected: video.isCollected }">⭐</text>
                </view>
                <text class="action-count">{{ formatCount(video.collectionsCount) }}</text>
              </view>
              <view class="action-item" @tap="shareVideo(video)">
                <view class="action-icon-wrapper">
                  <text class="action-icon">📤</text>
                </view>
                <text class="action-count">分享</text>
              </view>
              <view class="action-item" @tap="goToUserProfile(video.authorId)">
                <image class="action-avatar" :src="video.author?.avatar || '/static/logo.png'" mode="aspectFill">
                </image>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 加载提示 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 自定义 TabBar -->
    <custom-tabbar :current="1" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import { getWorksList, toggleLike as toggleLikeApi, toggleCollect as toggleCollectApi, type WorkInfo, MediaTypeEnum } from '@/api/works'
import { sendFriendRequest } from '@/api/friends'
import { useUser } from '@/composables/useUser'

// Tab标签（只保留推荐和关注）
const tabs = ref([
  { name: '推荐', type: 'recommend' },
  { name: '关注', type: 'follow' }
])

type VideoItem = WorkInfo & {
  isFollowed?: boolean
  followLoading?: boolean
}

const currentTab = ref(0)
const currentVideoIndex = ref(0)
const videoList = ref<VideoItem[]>([])
const loading = ref(false)
const page = ref(1)
const limit = ref(10)
const hasMore = ref(true)

// 视频播放器上下文
const videoContexts = ref<Map<number, any>>(new Map())

// 当前用户
const { userInfo, initUser } = useUser()
initUser()
const currentUserId = computed(() => userInfo.value?.id || 0)

// 格式化数字（超过1万显示为"1.2w"）
const formatCount = (count: number): string => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + 'w'
  }
  return String(count || 0)
}

// 切换Tab
const switchTab = async (index: number) => {
  if (currentTab.value === index) return

  currentTab.value = index
  currentVideoIndex.value = 0
  videoList.value = []
  page.value = 1
  hasMore.value = true

  // 暂停当前视频
  pauseAllVideos()

  // 加载新Tab的数据
  await loadVideos()
}

// 加载视频列表
const loadVideos = async () => {
  if (loading.value || !hasMore.value) return

  loading.value = true
  try {
    const params: any = {
      page: page.value,
      limit: limit.value,
      status: 'published' // 只获取已发布的作品
    }

    // 根据Tab类型加载不同数据
    if (currentTab.value === 0) {
      // 推荐：获取所有视频
      params.mediaType = MediaTypeEnum.VIDEO
    } else {
      // 关注：获取关注用户的视频（这里需要后端支持，暂时也用推荐逻辑）
      params.mediaType = MediaTypeEnum.VIDEO
    }

    const response = await getWorksList(params)

    if (response.data && response.data.length > 0) {
      // 过滤出视频类型并增强关注状态
      const videos = response.data
        .filter(work => work.mediaType === MediaTypeEnum.VIDEO && work.videoUrl)
        .map(work => ({
          ...work,
          isFollowed: (work as VideoItem).isFollowed ?? false,
          followLoading: false
        })) as VideoItem[]

      if (page.value === 1) {
        videoList.value = videos
      } else {
        videoList.value.push(...videos)
      }

      hasMore.value = response.data.length >= limit.value
      page.value++
    } else {
      hasMore.value = false
    }
  } catch (error: any) {
    console.error('加载视频列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 视频切换
const onVideoChange = (e: any) => {
  const newIndex = e.detail.current
  const oldIndex = currentVideoIndex.value

  currentVideoIndex.value = newIndex

  // 暂停旧视频
  pauseVideo(oldIndex)

  // 播放新视频
  playVideo(newIndex)

  // 如果接近底部，加载更多
  if (newIndex >= videoList.value.length - 2 && hasMore.value) {
    loadVideos()
  }
}

// 视频过渡
const onVideoTransition = (e: any) => {
  // 可以在这里添加过渡动画
}

// 播放视频
const playVideo = (index: number) => {
  if (index < 0 || index >= videoList.value.length) return

  const video = videoList.value[index]
  if (!video || !video.videoUrl) return

  const videoId = `video-${video.id || index}`
  const videoContext = uni.createVideoContext(videoId)

  if (videoContext) {
    videoContexts.value.set(index, videoContext)
    setTimeout(() => {
      videoContext.play()
    }, 100)
  }
}

// 暂停视频
const pauseVideo = (index: number) => {
  if (index < 0 || index >= videoList.value.length) return

  const videoContext = videoContexts.value.get(index)
  if (videoContext) {
    videoContext.pause()
  }
}

// 暂停所有视频
const pauseAllVideos = () => {
  videoContexts.value.forEach((context) => {
    context.pause()
  })
}

// 视频播放事件
const onVideoPlay = (e: any) => {
  console.log('视频开始播放:', e)
}

// 视频暂停事件
const onVideoPause = (e: any) => {
  console.log('视频暂停:', e)
}

// 视频结束事件
const onVideoEnded = (e: any) => {
  console.log('视频播放结束:', e)
  // 自动播放下一个（如果设置了loop则不会触发）
}

// 视频错误事件
const onVideoError = (e: any) => {
  console.error('视频播放错误:', e)
  uni.showToast({
    title: '视频加载失败',
    icon: 'none'
  })
}

// 切换点赞
const toggleLike = async (video: WorkInfo) => {
  try {
    const response = await toggleLikeApi(video.id)
    video.isLiked = response.isLiked
    // 根据操作更新点赞数
    if (response.action === 'liked') {
      video.likesCount = (video.likesCount || 0) + 1
    } else {
      video.likesCount = Math.max(0, (video.likesCount || 0) - 1)
    }
  } catch (error: any) {
    console.error('点赞失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  }
}

// 切换收藏
const toggleCollect = async (video: WorkInfo) => {
  try {
    const response = await toggleCollectApi(video.id)
    video.isCollected = response.isCollected
    // 根据操作更新收藏数
    if (response.action === 'collected') {
      video.collectionsCount = (video.collectionsCount || 0) + 1
    } else {
      video.collectionsCount = Math.max(0, (video.collectionsCount || 0) - 1)
    }
    uni.showToast({
      title: video.isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    })
  } catch (error: any) {
    console.error('收藏失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  }
}

// 跳转到评论
const goToComments = (workId: number) => {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${workId}&tab=comments`
  })
}

// 跳转到用户主页
const goToUserProfile = (userId: number) => {
  // TODO: 实现用户主页跳转
  uni.showToast({
    title: '用户主页',
    icon: 'none'
  })
}

// 分享视频
const shareVideo = (video: WorkInfo) => {
  // TODO: 实现分享功能
  uni.showShareMenu({
    withShareTicket: true
  })
  uni.showToast({
    title: '分享功能',
    icon: 'none'
  })
}

// 关注作者
const handleFollowAuthor = async (video: VideoItem) => {
  if (!video || video.followLoading || video.isFollowed || !video.authorId) return
  if (video.authorId === currentUserId.value) return

  video.followLoading = true
  try {
    await sendFriendRequest({
      friendId: video.authorId,
      remark: `我在生活记里关注了你`
    })
    video.isFollowed = true
    uni.showToast({
      title: '已关注',
      icon: 'success'
    })
  } catch (error: any) {
    console.error('关注失败:', error)
    uni.showToast({
      title: error.message || '关注失败',
      icon: 'none'
    })
  } finally {
    video.followLoading = false
  }
}

// 页面显示时
onShow(() => {
  // 恢复播放当前视频
  if (videoList.value.length > 0) {
    playVideo(currentVideoIndex.value)
  }
})

// 页面隐藏时
onHide(() => {
  // 暂停所有视频
  pauseAllVideos()
})

// 页面加载
onMounted(() => {
  loadVideos()
})

// 页面卸载
onUnmounted(() => {
  pauseAllVideos()
  videoContexts.value.clear()
})
</script>

<style scoped>
.recommend-container {
  width: 100%;
  height: 100vh;
  background-color: #000;
  display: flex;
  flex-direction: column;
  padding-bottom: 100rpx;
}

/* Tab栏 */
.tab-bar {
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  padding-top: var(--status-bar-height, 20px);
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
}

.tab-item.active .tab-text {
  color: #fff;
  font-weight: bold;
  font-size: 32rpx;
}

.tab-indicator {
  width: 60rpx;
  height: 6rpx;
  background-color: #fff;
  border-radius: 3rpx;
  margin-top: 10rpx;
}

/* 视频流 */
.video-swiper {
  flex: 1;
  width: 100%;
  height: 100%;
  margin-top: 88rpx;
}

.video-item-wrapper {
  width: 100%;
  height: 100%;
}

.video-item {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #000;
}

.video-player {
  width: 100%;
  height: 100%;
}

/* 视频信息遮罩层 */
.video-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 30rpx;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.6) 0%, transparent 50%);
  pointer-events: none;
}

/* 左侧信息 */
.video-info-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  gap: 20rpx;
  padding-bottom: 70rpx;
  pointer-events: auto;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.author-avatar-wrapper {
  position: relative;
  display: inline-flex;
}

.author-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
}

.follow-plus {
  position: absolute;
  bottom: -8rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7a45 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 28rpx;
  font-weight: 600;
  border: 3rpx solid #000;
  pointer-events: auto;
}

.followed-badge {
  position: absolute;
  bottom: -12rpx;
  right: -10rpx;
  padding: 6rpx 16rpx;
  border-radius: 30rpx;
  background-color: rgba(255, 255, 255, 0.85);
  color: #333;
  font-size: 22rpx;
  pointer-events: none;
}

.followed-text {
  font-size: 20rpx;
}

.author-name {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

.video-description {
  max-width: 500rpx;
}

.description-text {
  font-size: 28rpx;
  color: #fff;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag {
  font-size: 24rpx;
  color: #4A90E2;
  background-color: rgba(74, 144, 226, 0.2);
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

/* 右侧互动按钮 */
.video-actions-right {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  gap: 40rpx;
  padding-bottom: 70rpx;
  pointer-events: auto;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.action-icon-wrapper {
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  backdrop-filter: blur(10rpx);
}

.action-icon {
  font-size: 48rpx;
  transition: transform 0.2s;
}

.action-icon.liked {
  animation: likeAnimation 0.3s;
}

.action-icon.collected {
  animation: likeAnimation 0.3s;
}

@keyframes likeAnimation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.3);
  }

  100% {
    transform: scale(1);
  }
}

.action-count {
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
}

.action-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  border: 4rpx solid #fff;
}

/* 加载提示 */
.loading-overlay {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 200;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #fff;
}

/* 空视频占位 */
.empty-video-placeholder {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 0 60rpx;
}

.empty-video-card {
  width: 100%;
  border-radius: 32rpx;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.02));
  border: 1rpx solid rgba(255, 255, 255, 0.1);
  padding: 80rpx 40rpx;
  text-align: center;
  color: #fff;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-title {
  font-size: 34rpx;
  font-weight: 600;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 40rpx;
}

.empty-action {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 50rpx;
  border-radius: 999rpx;
  background: linear-gradient(135deg, #4a90e2, #6dd5fa);
  color: #0c1b2b;
  font-size: 28rpx;
  font-weight: 600;
}
</style>
